package fr.syntheses.blog.Service;







import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import fr.syntheses.blog.Model.DAO.HibernateUtil;
import fr.syntheses.blog.beans.Style;







/**
 * @author ---------------
 * 21 oct 2012
 * ApplicationListener.java
 * Test service hibernate
 */
/**
 * @author Altenide-mov
 *
 */
public class ApplicationListener implements ServletContextListener {

	//-------------------------------------------------------------
	// Properties
	//-------------------------------------------------------------		

	/**
	 * init session hibernate.
	 */
	private Session session = null;	

	/**
	 * Le context.
	 */
	private Context context = null;


	/**
	 * La transaction.
	 */
	private Transaction transaction;

	/**
	 * La sessionFactory.
	 */
	private static SessionFactory sessionFactory;


	/**
	 * serviceRegistry.
	 */
	private static ServiceRegistry serviceRegistry;

	//-------------------------------------------------------------
	// Init
	//-------------------------------------------------------------	

	/**
	 * Le logguer log4j.
	 */
	private Logger log = Logger.getLogger(ApplicationListener.class);	




	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public final void contextInitialized(ServletContextEvent servletContextEvent) 
	{
		// boot

		ServletContext servletContext = servletContextEvent.getServletContext();


		log.info("/* Initialisation du context pour " +   servletContext.getContextPath() + " */");

		String dataSourceJNDI = servletContext.getInitParameter("dataSourceJNDI");

		try
		{
			context = new InitialContext();

			DataSource dataSource = (DataSource) context.lookup(dataSourceJNDI);

			if (dataSource == null)
			{
				log.fatal("Erreur lors de l'instanciation de la data source : Veuillez vï¿½rifier vos fichiers web.xml et context.xml");
			}
			else
			{
				// on stocke la dataSource dans le contexte
				log.info("/*  La dataSource a ï¿½tï¿½ instanciï¿½ et stockï¿½e avec success */");
			}

		}
		catch (NamingException e)
		{
			log.fatal("Erreur lors de l'instanciation de la data source " + e);
			throw new RuntimeException();
		}
		finally
		{
			try
			{
				// Fermeture du contexte
				if (context != null)
				{
					context.close();
				}
			}
			catch (Exception e)
			{   
				log.fatal(" grave erreur lors de l'initialisation du context : " + e);
			}
		}

		try {
			

			log.info("/* SessionFactory hibernate crï¿½ï¿½e avec succï¿½s */");


			// transaction neutre pour la creation de la base (ou sa mise a jour a chaque rechargement du contexte).
			try {


//				Configuration configuration = new Configuration();
//
//				configuration.configure();
//
//				serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();   
//
//				sessionFactory = configuration.buildSessionFactory(serviceRegistry);	

				HibernateUtil.createSessionFactory();

				session = HibernateUtil.getSession();
				
				transaction =  session.beginTransaction(); 	
				
				Style style = new Style();

				style.setId(1);
				style.setStyle("Rouge");
				
				session.save(style);

				transaction.commit();
				
				session.flush();
				
				session.delete(style);

				log.info("/* SUCCESS TRANSACTION TEST */");


			} catch (Exception e) {
				log.fatal(e.getMessage());
				e.printStackTrace();
				if (transaction != null) {
					transaction.rollback();
				}
			}

			finally {
				session.flush();
				session.close();
			}




		} catch (HibernateException e) {

			log.fatal("/* ------------------------------------------------------------------- */");
			log.fatal("/* ATTENTION GRAVE ERREUR LORS DE LA CREATION DE LA SESSION FACTORY HB */");
			log.fatal(e);
			log.fatal("");
			log.fatal("/*    l'application ne peut dï¿½marrer suite aux erreurs prï¿½cï¿½dentes     */");
			log.fatal("/* ------------------------------------------------------------------- */");
			
			servletContext.setAttribute("dataSource", null);

			try {
				throw new ServletException(e);
			} catch (ServletException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}		
	}



	public final void contextDestroyed(final ServletContextEvent servletContextEvent)
	{
		ServletContext servletContext = servletContextEvent.getServletContext();
	// why not !!! 	HibernateUtil.closeSessionFactory();
		log.info("/* Destruction du context pour " +   servletContext.getContextPath() + " */");
	}
}
